package com.course.controller;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.*;

import com.course.db.ChooseCourse;
import com.course.db.CourseBasic;
import com.course.db.OpenCourse;
import com.course.db.Pages;
import com.course.db.Teacher;
import com.et.mvc.JspView;

public class TeacherController  extends ApplicationController {
	
	//apply for opening a new course
	public JspView apply() throws Exception{
		

	       String src=request.getParameter("src");
	       String type=request.getParameter("type");
		   JspView view = new JspView("index.jsp");
	       System.out.println("apply");
	       
	       String strUserID = request.getSession().getAttribute("userID").toString();
	       
	       int teacher_id = 0;
	       Teacher teacher = new Teacher();
	       teacher.setUser_id(Integer.parseInt(strUserID));
	       teacher_id = teacher.teacher_id();

	       CourseBasic course = new CourseBasic();

	       if(src.equalsIgnoreCase("edit"))
	       {
	    	   course.setId(Integer.parseInt(request.getParameter("courseId")));
	    	   course.init();
	       }
	       
//	       response.setContentType("text/xml; charset=UTF-8");
	       String teacher_name=request.getParameter("teacher_name");
	       String course_type=request.getParameter("course_type");
	       String course_name=request.getParameter("course_name");
	       String course_span=request.getParameter("course_span");
	       String credit=request.getParameter("credit");
	       String students_max=request.getParameter("students_max");
	       String students_min=request.getParameter("students_min");
	       String year=request.getParameter("year");
	       String [] terms=request.getParameterValues("term");
	       String [] grades=request.getParameterValues("grade");
	       String time=request.getParameter("time");
	       String location=request.getParameter("location");
	       String teach_style=request.getParameter("teach_style");
	       String test_style=request.getParameter("test_style");
	       String equipments=request.getParameter("equipments");
	       String introduction=request.getParameter("introduction");
	       
	       String course_term = "", course_grade = "";
	       String strclassno = "";
	       strclassno += year.substring(0, year.length()-1);
	       if(terms!=null && terms[0] != null && !terms[0].equalsIgnoreCase(""))
	       {
		       if(terms[0].equalsIgnoreCase("第一学期"))
		    	   strclassno += "1";
		       else if(terms[0].equalsIgnoreCase("第二学期"))
		    	   strclassno += "2";
		       else if(terms[0].equalsIgnoreCase("第三学期"))
		    	   strclassno += "3";
		       else
	    	   strclassno += "4";
	       }
	       else
	    	   strclassno +="0";
	       
	       if(!src.equalsIgnoreCase("edit"))
	       {
		       //new method
		       int num = course.count();
			   System.out.println("num:"+num);
			   if(num+1>1000)
			   {
				   num = 0;
			   }
			   if(num+1<10)
			   {
			    	strclassno += "00";
			   }
			   else if(num+1<100)
			   {
			    	strclassno += "0";
			   }
			   strclassno += String.valueOf(num+1);
		       course.setClassno(strclassno);
	       }
	       
	       course.setTeachers(teacher_name);
	       course.setType(course_type);
	       course.setName(course_name);
	       if(course_span != null && !course_span.equalsIgnoreCase(""))
	    	   course.setCourse_span( Integer.parseInt(course_span) );

	       if(credit != null && !credit.equalsIgnoreCase(""))
	    	   course.setCredit( Double.parseDouble(credit) );

	       if(students_max != null && !students_max.equalsIgnoreCase(""))
	    	   course.setStudents_high( Integer.parseInt(students_max) );

	       if(students_min != null && !students_min.equalsIgnoreCase(""))
	    	   course.setStudents_low( Integer.parseInt(students_min) );
	       course.setYear(year);
	       if(terms!=null && terms[0] != null && !terms[0].equalsIgnoreCase(""))
	       {
		       for(int i=0; i<terms.length; i++)
		       {
		    	   course_term += terms[i];
		    	   course_term += " ";
		       }
		       course.setOpenterm(course_term);
	       }
	       
	       if(grades!=null && grades[0] != null && !grades[0].equalsIgnoreCase(""))
	       {
		       for(int i=0; i<grades.length; i++)
		       {
		    	   course_grade += grades[i];
		    	   course_grade += " ";
		       }
		       course.setGrade(course_grade);
	       }
	       
	       course.setTeach_time(time);
	       course.setTeach_location(location);
	       course.setTeach_style(teach_style);
	       course.setTest_style(test_style);
	       course.setTeach_equipments(equipments);
	       course.setIntroduction(introduction);
	       if(src.equalsIgnoreCase("admin"))
	    	   course.setCheck_status(1);
	       
	      
	       if(!src.equalsIgnoreCase("edit")&&course.add())
	       {
	    	   System.out.println(" Add Course Ok!");
	    	   OpenCourse open_course = new OpenCourse();
	    	   open_course.setCheck_status(0);
	    	   open_course.setNum_choose_students(0);
	    	   open_course.setCourse_id(course.lastid());
	    	   open_course.setTeacher_id(teacher_id);
	    	   
	    	   if(open_course.add())
	    		   System.out.println(" Add opencourse Ok!");
	    	   else
	    		   System.out.println(" Add opencourse False!");
	    		   
	       }
	       else if(src.equalsIgnoreCase("edit"))
	    	   course.modify_coursebasic();
	       else
	    	   System.out.println(" Add Course False!");
	       
	       String user_type=request.getParameter("type");
	       if(src.equalsIgnoreCase("teacher")||(user_type!=null &&user_type.equalsIgnoreCase("teacher")))
	    	   response.sendRedirect("myCourse.do");
	       else
	    	   response.sendRedirect("../Admin/manage.do");
	       return null;
	}
	
	//apply for opening a new course
	public String editCourse() throws Exception{
		

	       String src=request.getParameter("src");
	       String type=request.getParameter("type");
	       System.out.println("apply");
	       
	       String strUserID = request.getSession().getAttribute("userID").toString();
	       
	       int teacher_id = 0;
	       Teacher teacher = new Teacher();
	       teacher.setUser_id(Integer.parseInt(strUserID));
	       teacher_id = teacher.teacher_id();

	       CourseBasic course = new CourseBasic();

	       if(src.equalsIgnoreCase("edit"))
	       {
	    	   course.setId(Integer.parseInt(request.getParameter("courseId")));
	    	   course.init();
	       }
	       
//	       response.setContentType("text/xml; charset=UTF-8");
	       String teacher_name=request.getParameter("teacher_name");
	       String course_type=request.getParameter("course_type");
	       String course_name=request.getParameter("course_name");
	       String course_span=request.getParameter("course_span");
	       String credit=request.getParameter("credit");
	       String students_max=request.getParameter("students_max");
	       String students_min=request.getParameter("students_min");
	       String year=request.getParameter("year");
	       String [] terms=request.getParameterValues("term");
	       String [] grades=request.getParameterValues("grade");
	       String time=request.getParameter("time");
	       String location=request.getParameter("location");
	       String teach_style=request.getParameter("teach_style");
	       String test_style=request.getParameter("test_style");
	       String equipments=request.getParameter("equipments");
	       String introduction=request.getParameter("introduction");
	       
	       String course_term = "", course_grade = "";
	       String strclassno = "";
	       strclassno += year.substring(0, year.length()-1);
	       if(terms!=null && terms[0] != null && !terms[0].equalsIgnoreCase(""))
	       {
		       if(terms[0].equalsIgnoreCase("第一学期"))
		    	   strclassno += "1";
		       else if(terms[0].equalsIgnoreCase("第二学期"))
		    	   strclassno += "2";
		       else if(terms[0].equalsIgnoreCase("第三学期"))
		    	   strclassno += "3";
		       else
	    	   strclassno += "4";
	       }
	       else
	    	   strclassno +="0";
	       
	       if(!src.equalsIgnoreCase("edit"))
	       {
		       //new method
		       int num = course.count();
			   System.out.println("num:"+num);
			   if(num+1>1000)
			   {
				   num = 0;
			   }
			   if(num+1<10)
			   {
			    	strclassno += "00";
			   }
			   else if(num+1<100)
			   {
			    	strclassno += "0";
			   }
			   strclassno += String.valueOf(num+1);
		       course.setClassno(strclassno);
	       }
	       
	       course.setTeachers(teacher_name);
	       course.setType(course_type);
	       course.setName(course_name);
	       if(course_span != null && !course_span.equalsIgnoreCase(""))
	    	   course.setCourse_span( Integer.parseInt(course_span) );

	       if(credit != null && !credit.equalsIgnoreCase(""))
	    	   course.setCredit( Double.parseDouble(credit) );

	       if(students_max != null && !students_max.equalsIgnoreCase(""))
	    	   course.setStudents_high( Integer.parseInt(students_max) );

	       if(students_min != null && !students_min.equalsIgnoreCase(""))
	    	   course.setStudents_low( Integer.parseInt(students_min) );
	       course.setYear(year);
	       if(terms!=null && terms[0] != null && !terms[0].equalsIgnoreCase(""))
	       {
		       for(int i=0; i<terms.length; i++)
		       {
		    	   course_term += terms[i];
		    	   course_term += " ";
		       }
		       course.setOpenterm(course_term);
	       }
	       
	       if(grades!=null && grades[0] != null && !grades[0].equalsIgnoreCase(""))
	       {
		       for(int i=0; i<grades.length; i++)
		       {
		    	   course_grade += grades[i];
		    	   course_grade += " ";
		       }
		       course.setGrade(course_grade);
	       }
	       
	       course.setTeach_time(time);
	       course.setTeach_location(location);
	       course.setTeach_style(teach_style);
	       course.setTest_style(test_style);
	       course.setTeach_equipments(equipments);
	       course.setIntroduction(introduction);
	       if(src.equalsIgnoreCase("admin"))
	    	   course.setCheck_status(1);
	       
	      
	       if(!src.equalsIgnoreCase("edit")&&course.add())
	       {
	    	   System.out.println(" Add Course Ok!");
	    	   OpenCourse open_course = new OpenCourse();
	    	   open_course.setCheck_status(0);
	    	   open_course.setNum_choose_students(0);
	    	   open_course.setCourse_id(course.lastid());
	    	   open_course.setTeacher_id(teacher_id);
	    	   
	    	   if(open_course.add())
	    		   System.out.println(" Add opencourse Ok!");
	    	   else
	    		   System.out.println(" Add opencourse False!");
	    		   
	       }
	       else if(src.equalsIgnoreCase("edit"))
	    	   course.modify_coursebasic();
	       else
	    	   System.out.println(" Add Course False!");
	       
	       String user_type=request.getParameter("type");
	       if(src.equalsIgnoreCase("edit") && type.equals("teacher"))
	    	   return "<script type=\"text/javascript\">function closebox(){ top.location.href=\"../Teacher/myCourse.do\"; this.parent.Popup.prototype.reset_m();}</script><link rel=\"stylesheet\" href=\"/css/style.css\" />编辑成功！<a href=\"javascript:closebox();\">关闭</a>";
	       else if(src.equalsIgnoreCase("edit") && type.equals("admin"))
	    	   return "<script type=\"text/javascript\">function closebox(){ top.location.href=\"../Admin/manage.do\"; this.parent.Popup.prototype.reset_m();}</script><link rel=\"stylesheet\" href=\"/css/style.css\" />编辑成功！<a href=\"javascript:closebox();\">关闭</a>";
	       else if(src.equalsIgnoreCase("teacher")||(user_type!=null &&user_type.equalsIgnoreCase("teacher")))
	    	   response.sendRedirect("myCourse.do");
	       else
	    	   response.sendRedirect("../Admin/manage.do");
	       return null;
	}
	

	//check out my opening class
	public JspView myCourse() throws Exception{
		
		   JspView view = new JspView("teacher/mycourse.jsp");
	       System.out.println("mycourse");
	       
	       String strUserID = request.getSession().getAttribute("userID").toString();
	       
	       int teacher_id = 0;
	       Teacher teacher = new Teacher();
	       teacher.setUser_id(Integer.parseInt(strUserID));
	       teacher_id = teacher.teacher_id();
	       teacher.setId(teacher_id);
	       ResultSet courseRs = teacher.show_courses();
	       //request.getSession().setAttribute("myOpenCourse", courseRs);
	       
	       List< Hashtable<String, String> > courseList = new ArrayList< Hashtable<String, String> >();
	       List< Hashtable<String, String> > courseListTemp = new ArrayList< Hashtable<String, String> >();
	       try{
				String value="";
				ResultSetMetaData courseRsMd = courseRs.getMetaData();
				int cols = courseRsMd.getColumnCount();
				while (courseRs.next())
				{
					Hashtable<String, String> hash = new Hashtable<String, String>();
					for (int i = 1; i <= cols; i++) {	
						String field = (String) (courseRsMd.getColumnName(i));
						int fieldtype = courseRsMd.getColumnType(i);
						if(fieldtype == java.sql.Types.VARCHAR )
							value = (String) (courseRs.getString(i));
						else if(fieldtype == java.sql.Types.DOUBLE)
							value = (String)(Double.toString(courseRs.getDouble(i)));
						else if(fieldtype == java.sql.Types.INTEGER)
							value = (String)(Integer.toString(courseRs.getInt(i)));
						else if(fieldtype == java.sql.Types.BIGINT)
							value = (String)(Integer.toString(courseRs.getInt(i)));
						else if(fieldtype == java.sql.Types.SMALLINT)
							value = (String)(Integer.toString(courseRs.getInt(i)));
						else if(fieldtype == java.sql.Types.TINYINT)
							value = (String)(Integer.toString(courseRs.getInt(i)));
						else if(fieldtype == java.sql.Types.CHAR)
							value = (String) (courseRs.getString(i));
						else if(fieldtype == java.sql.Types.DATE)
							value = (String) (courseRs.getDate(i).toString());
						
						if (value == null)
							value = "";
						hash.put(field, value);
					}
					courseListTemp.add(hash);
				}
				
				request.setAttribute("TeacherCourseList", courseList);
				
			}catch(Exception e){
				e.printStackTrace();
			}
			
			Pages page = new Pages();
			String parameters = "page=page";
			page.setIntPageSize(15);
			page.InitPage(parameters,courseListTemp.size(), request);
			String footer = page.PageFooter(); 
			session.setAttribute("TeaCrListPageFooter", footer);
			
			int intPageCount = page.getIntPageCount();
			int intPage = page.getIntPage();
			int intPageSize = page.getIntPageSize();
			
			Iterator<Hashtable<String, String>> user_it = courseListTemp.iterator();
			if (intPageCount>0)  
	        {  
				System.out.println("intPageCount:"+intPageCount);
				System.out.println("intPageSize:"+intPageSize);
				System.out.println("intPage:"+intPage);
				
	           int nowpage=0; 
		    	while(user_it.hasNext())
				{
		    		Hashtable<String, String> userlist_hash  = user_it.next();
		    		nowpage++;
					if (nowpage>((intPage-1)*intPageSize) &&(nowpage<=intPage*intPageSize))  
		            {
						Hashtable<String, String> hash = new Hashtable<String, String>();
						for(Iterator itr = userlist_hash.keySet().iterator(); itr.hasNext();)
						{
							String key = (String) itr.next();
							String value = (String) userlist_hash.get(key);

							if(value != null)
								hash.put(key, value);
							else
								hash.put(key, "");
						}

						courseList.add(hash);
		            }
				}
	        }
		
		   request.setAttribute("TeacherCourseList", courseList);
	       
	       return view;
	}
	public JspView coursedetail() throws Exception{
		
		JspView view = new JspView("search/coursedetail.jsp");
		System.out.println("detail");
		System.out.println("id:"+request.getParameter("courseId").trim());
		int courseId = Integer.parseInt( request.getParameter("courseId").trim());
		CourseBasic course =new CourseBasic();
		course.setId(courseId);
		course.init();
		session.setAttribute("Course", course);
		
		ChooseCourse choosecourse = new ChooseCourse();
		choosecourse.setCourse_id(courseId);
		ResultSet studentRs = choosecourse.show_course_student(courseId);
		
		List< Hashtable<String, String> > coursestudentList = new ArrayList< Hashtable<String, String> >();
		try{
			String value="";
			ResultSetMetaData courseRsMd = studentRs.getMetaData();
			int cols = courseRsMd.getColumnCount();
			while (studentRs.next())
			{
				Hashtable<String, String> hash = new Hashtable<String, String>();
				for (int i = 1; i <= cols; i++) {	
					String field = (String) (courseRsMd.getColumnName(i));
					int fieldtype = courseRsMd.getColumnType(i);
					if(fieldtype == java.sql.Types.VARCHAR )
						value = (String) (studentRs.getString(i));
					else if(fieldtype == java.sql.Types.DOUBLE)
						value = (String)(Double.toString(studentRs.getDouble(i)));
					else if(fieldtype == java.sql.Types.INTEGER)
						value = (String)(Integer.toString(studentRs.getInt(i)));
					else if(fieldtype == java.sql.Types.BIGINT)
						value = (String)(Integer.toString(studentRs.getInt(i)));
					else if(fieldtype == java.sql.Types.SMALLINT)
						value = (String)(Integer.toString(studentRs.getInt(i)));
					else if(fieldtype == java.sql.Types.TINYINT)
						value = (String)(Integer.toString(studentRs.getInt(i)));
					else if(fieldtype == java.sql.Types.CHAR)
						value = (String) (studentRs.getString(i));
					else if(fieldtype == java.sql.Types.DATE)
						value = (String) (studentRs.getDate(i).toString());
					
					if (value == null)
						value = "";
					hash.put(field, value);
				}
				coursestudentList.add(hash);
			}
			
			session.setAttribute("CourseStudentList", coursestudentList);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		/*
		response.sendRedirect("../admin/coursechooseDetail.jspx");
		
		return null;
		
		JspView view = new JspView("search/coursedetail.jsp");
		System.out.println("coursedetail");
		int courseId = Integer.parseInt( request.getParameter("courseId").trim());
		CourseBasic course =new CourseBasic();
		course.setId(courseId);
		course.init();
		request.setAttribute("Course", course);
		*/
		
		response.sendRedirect("../search/coursedetail.jspx");
		return null;
	}
	
public JspView gradestudents() throws Exception{
		
		System.out.println("detail");
		System.out.println("id:"+request.getParameter("courseId").trim());
		int courseId = Integer.parseInt( request.getParameter("courseId").trim());
		CourseBasic course =new CourseBasic();
		course.setId(courseId);
		course.init();
		session.setAttribute("Course", course);
		
		ChooseCourse choosecourse = new ChooseCourse();
		choosecourse.setCourse_id(courseId);
		ResultSet studentRs = choosecourse.show_course_student(courseId);
		
		List< Hashtable<String, String> > coursestudentList = new ArrayList< Hashtable<String, String> >();
		try{
			String value="";
			ResultSetMetaData courseRsMd = studentRs.getMetaData();
			int cols = courseRsMd.getColumnCount();
			while (studentRs.next())
			{
				Hashtable<String, String> hash = new Hashtable<String, String>();
				for (int i = 1; i <= cols; i++) {	
					String field = (String) (courseRsMd.getColumnName(i));
					int fieldtype = courseRsMd.getColumnType(i);
					if(fieldtype == java.sql.Types.VARCHAR )
						value = (String) (studentRs.getString(i));
					else if(fieldtype == java.sql.Types.DOUBLE)
						value = (String)(Double.toString(studentRs.getDouble(i)));
					else if(fieldtype == java.sql.Types.INTEGER)
						value = (String)(Integer.toString(studentRs.getInt(i)));
					else if(fieldtype == java.sql.Types.BIGINT)
						value = (String)(Integer.toString(studentRs.getInt(i)));
					else if(fieldtype == java.sql.Types.SMALLINT)
						value = (String)(Integer.toString(studentRs.getInt(i)));
					else if(fieldtype == java.sql.Types.TINYINT)
						value = (String)(Integer.toString(studentRs.getInt(i)));
					else if(fieldtype == java.sql.Types.CHAR)
						value = (String) (studentRs.getString(i));
					else if(fieldtype == java.sql.Types.DATE)
						value = (String) (studentRs.getDate(i).toString());
					
					if (value == null)
						value = "";
					hash.put(field, value);
				}
				coursestudentList.add(hash);
			}
			
			session.setAttribute("GradeStudentList", coursestudentList);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		response.sendRedirect("../teacher/gradestudent.jspx");
		return null;
	}

public String gradeasure() throws Exception{

	List<Hashtable<String, String>> student_list = (List<Hashtable<String, String>>) session.getAttribute("GradeStudentList");
	Iterator<Hashtable<String, String>> student_it = student_list.iterator();
	
	ChooseCourse choosecourse = new ChooseCourse();
	while(student_it.hasNext())
	{
		Hashtable<String, String> studentlist_hash  = student_it.next();
		String choose_id = studentlist_hash.get("choose_Id");
		choosecourse.setId(Integer.parseInt(choose_id));
		choosecourse.init();
		String score = request.getParameter(choose_id);
		if(score!=null&&!score.trim().equals(""))
			choosecourse.setScore(score);
		choosecourse.modify_choose_course();
	}
	return "<script type=\"text/javascript\">function closebox(){top.location.href=\"../Teacher/myCourse.do\" ; this.parent.Popup.prototype.reset_mm();}</script><link rel=\"stylesheet\" href=\"/css/style.css\" />评分成功！<a href=\"javascript:closebox();\">关闭</a>";	
}

public String edit() throws Exception{
		
		System.out.println("teacher edit");
		int teacherId = Integer.parseInt( request.getParameter("teacherId").trim());
		Teacher teacher =new Teacher();
		teacher.setId(teacherId);
		teacher.init();
		teacher.setName(request.getParameter("name"));
		
		teacher.modify_teacher();
		
		return "<script type=\"text/javascript\">function closebox(){top.location.href=\"../Admin/userList.do?tab=1\" ; this.parent.Popup.prototype.reset_m();}</script><link rel=\"stylesheet\" href=\"/css/style.css\" />修改成功！<a href=\"javascript:closebox();\">关闭</a>";	
	}

}
